<?php

namespace App\Service;

use App\Model\QuestionModel;
use App\Model\QuestionnaireItemModel;
use App\Model\QuestionnaireModel;
use EasySwoole\Mysqli\Exception\Exception;
use Throwable;

class QuestionnaireService extends BaseService
{
    /**
     * @return array
     * @throws Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws Throwable
     */
    function getQuestionStatus(): array
    {
        $status = QuestionnaireModel::create()->getQuestionnaire(['is_open' => 0]);

        if ($status) {
            return [
                'result' => true,
                'msg' => '获取成功',
                'data' => $status->toArray()
            ];
        }

        return [
            'result' => false,
            'msg' => '获取失败'
        ];
    }

    /**
     * @param $qid
     * @return array
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    function getQuestion($qid): array
    {
        $questions = QuestionnaireItemModel::create()->where(['qid' => $qid, 'is_deleted' => 0])->order('sort', 'asc')->all();
        if (empty($questions)) {
            return [
                'result' => false,
                'msg' => '暂无数据'
            ];
        }

        $data = [];
        foreach ($questions as $question) {
            $item = $question;
            $item['select'] = explode('|', $question['description']);
            $data[] = $item;
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => $data
        ];
    }

    /**
     * @param $id
     * @param $name
     * @param $tel
     * @param $house
     * @param $content
     * @return array
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    function setQuestion($id, $name, $tel, $house, $content): array
    {
        $log = QuestionModel::create()->getQuestionnaire(['tel' => $tel, 'qid' => $id]);
        if ($log){
            return [
                'result' => false,
                'msg' => '单个用户每次只能提交一次'
            ];
        }

        $param = [
            'qid' => $id,
            'name' => $name,
            'tel' => $tel,
            'house' => $house,
            'content' => $content
        ];

        $res = QuestionModel::create()->addQuestionnaire($param);

        if (!$res) {
            return [
                'result' => false,
                'msg' => '提交失败'
            ];
        }

        return [
            'result' => true,
            'msg' => '提交成功',
            'data' => null
        ];
    }
}